<?php

/**
 * 分销佣金结算
 */
defined('In33hao') or exit('Access Invalid!');

//会员，小店分销即时结算
function brokerageBill($order_info, $score = 0)
{
    $model_member = Model('member');
    $member_info = $model_member->getMemberInfoByID($order_info['buyer_id']);
    $settings = Model('setting')->getListSetting();
    //处理一级返佣
    if ($member_info['lev1'] && $order_info['invite_rates']) {
        dealMemberBrokerage($order_info, $member_info['lev1'], $order_info['invite_rates'], '一级');
    }
    //处理二级返佣
    if ($member_info['lev2'] && $order_info['invite_rates_two']) {
        dealMemberBrokerage($order_info, $member_info['lev2'], $order_info['invite_rates_two'], '二级');
    }
    try {
        $model_member->beginTransaction();
        //商城订单商品状态更新
        updateOrderGoods($order_info);
        //处理小店返佣
        dealStoremBrokerage($order_info, $settings);
        //处理代理返佣
        dealAgentBrokerage($order_info, $member_info, $settings);
        //处理商圈返利
        dealSqBrokerage($order_info, $score);
        $model_member->commit();
    } catch (Exception $e) {
        $model_member->rollback();
    }

}

function updateOrderGoods($order_info)
{
    //商圈订单直接返回
    if (isset($order_info['member_rates'])) {
        return true;
    }
    $model_order = Model('order');
    //更新order_goods表订单商品状态为已支付
    $result = $model_order->editOrderGoods(['order_status' => ORDER_STATE_PAY], ['order_id' => $order_info['order_id']]);
    if (!$result) {
        throw new Exception('订单商品更新失败');
    }

}

//处理会员返佣
function dealMemberBrokerage($order_info, $member_id, $brokerage, $level)
{
    $model_member = Model('member');
    $model_brokerage_log = Model('brokerage_log');
    $data['brokerage'] = ['exp', 'brokerage+' . $brokerage];
    $data['av_brokerage'] = ['exp', 'av_brokerage+' . $brokerage];
    $result = $model_member->editMember(['member_id' => $member_id], $data);
    if (!$result) {
        throw new Exception('会员信息更新失败');
    }
    //写入分销佣金日志
    $log['member_id'] = $member_id;
    $log['order_id'] = $order_info['order_id'];
    $log['order_sn'] = $order_info['order_sn'];
    $log['money'] = $brokerage;
    $log['type'] = 1;
    $log['description'] = $level . '返佣收入';
    $log['addtime'] = time();
    $result = $model_brokerage_log->addMemberLog($log);
    if (!$result) {
        throw new Exception('写入日志失败');
    }
}

//处理小店返佣
function dealStoremBrokerage($order_info, $settings)
{
    if (!$order_info['store_rates']) {
        return true;
    }
    $model_brokerage_log = Model('brokerage_log');
    $model_member = Model('member');
    $store = Model('store');
    if (isset($order_info['member_rates'])) {
        if ($order_info['my_store_id']) {
            $store_info = $store->getStoreInfo(['store_id' => $order_info['my_store_id']]);
            $member_info = $model_member->getMemberInfoByID($store_info['member_id']);
            $data = [];
            $data['store_brokerage'] = $member_info['store_brokerage'] + $order_info['store_rates'];
            $data['av_store_brokerage'] = $member_info['av_store_brokerage'] + $order_info['store_rates'];
            $result = $model_member->editMember(['member_id' => $store_info['member_id']], $data);
            if (!$result) {
                throw new Exception('会员信息更新失败');
            }
            //写入分销佣金日志
            $log['member_id'] = $store_info['member_id'];
            $log['store_id'] = $store_info['store_id'];
            $log['order_id'] = $order_info['order_id'];
            $log['order_sn'] = $order_info['order_sn'];
            $log['money'] = $order_info['store_rates'];
            $log['type'] = 1;
            $log['description'] = '小店返佣收入';
            $log['addtime'] = time();
            $result = $model_brokerage_log->addStoreLog($log);
            if (!$result) {
                throw new Exception('写入日志失败');
            }
            if ($member_info['invite_store']) {
                $store_info_one = $store->getStoreInfo(['member_id' => $member_info['invite_store']]);
                $fx_st_invite = 0;
                if ($store_info_one['type'] == 1) {
                    $fx_st_invite = $settings['fx_st_one_invite'];
                }
                if ($store_info_one['type'] == 2) {
                    $fx_st_invite = $settings['fx_st_two_invite'];
                }
                if ($store_info_one['type'] == 3) {
                    $fx_st_invite = $settings['fx_st_three_invite'];
                }
                if ($store_info_one['type'] == 4) {
                    $fx_st_invite = $settings['fx_st_four_invite'];
                }
                $rates = round($order_info['store_rates'] * $fx_st_invite / 100, 2);
                if (!$rates) {
                    return true;
                }
                $data = [];
                $data['store_brokerage'] = ['exp', 'store_brokerage+' . $rates];
                $data['av_store_brokerage'] = ['exp', 'av_store_brokerage+' . $rates];
                $result = $model_member->editMember(['member_id' => $member_info['invite_store']], $data);
                if (!$result) {
                    throw new Exception('会员信息更新失败');
                }
                $log = [];
                //写入分销佣金日志
                $log['member_id'] = $member_info['invite_store'];
                $log['store_id'] = $store_info_one['store_id'];
                $log['order_id'] = $order_info['order_id'];
                $log['order_sn'] = $order_info['order_sn'];
                $log['money'] = $rates;
                $log['type'] = 1;
                $log['description'] = '下级店铺利润返佣收入';
                $log['addtime'] = time();
                $result = $model_brokerage_log->addStoreLog($log);
                if (!$result) {
                    throw new Exception('写入日志失败');
                }
            }
        }
    } else {
        $order_goods = Model('order')->getOrderGoodsList(['order_id' => $order_info['order_id']]);
        foreach ($order_goods as $v) {
            if (!($v['my_store_id'] && $v['store_rates'])) {
                continue;
            }
            $store_info = $store->getStoreInfo(['store_id' => $v['my_store_id']]);
            $member_info = $model_member->getMemberInfoByID($store_info['member_id']);
            $data = [];
            $data['store_brokerage'] = $member_info['store_brokerage'] + $v['store_rates'];
            $data['av_store_brokerage'] = $member_info['av_store_brokerage'] + $v['store_rates'];
            $result = $model_member->editMember(['member_id' => $store_info['member_id']], $data);
            if (!$result) {
                throw new Exception('会员信息更新失败');
            }
            $log = [];
            //写入分销佣金日志
            $log['member_id'] = $store_info['member_id'];
            $log['store_id'] = $store_info['store_id'];
            $log['order_id'] = $order_info['order_id'];
            $log['order_sn'] = $order_info['order_sn'];
            $log['money'] = $v['store_rates'];
            $log['type'] = 1;
            $log['description'] = '小店返佣收入';
            $log['addtime'] = time();
            $result = $model_brokerage_log->addStoreLog($log);
            if (!$result) {
                throw new Exception('写入日志失败');
            }
            if ($member_info['invite_store']) {
                $store_info_one = $store->getStoreInfo(['member_id' => $member_info['invite_store']]);
                $fx_st_invite = 0;
                if ($store_info_one['type'] == 1) {
                    $fx_st_invite = $settings['fx_st_one_invite'];
                }
                if ($store_info_one['type'] == 2) {
                    $fx_st_invite = $settings['fx_st_two_invite'];
                }
                if ($store_info_one['type'] == 3) {
                    $fx_st_invite = $settings['fx_st_three_invite'];
                }
                if ($store_info_one['type'] == 4) {
                    $fx_st_invite = $settings['fx_st_four_invite'];
                }
                $rates = round($v['store_rates'] * $fx_st_invite / 100, 2);
                if (!$rates) {
                    continue;
                }
                $data = [];
                $data['store_brokerage'] = ['exp', 'store_brokerage+' . $rates];
                $data['av_store_brokerage'] = ['exp', 'av_store_brokerage+' . $rates];
                $result = $model_member->editMember(['member_id' => $member_info['invite_store']], $data);
                if (!$result) {
                    throw new Exception('会员信息更新失败');
                }
                $log = [];
                //写入分销佣金日志
                $log['member_id'] = $member_info['invite_store'];
                $log['store_id'] = $store_info_one['store_id'];
                $log['order_id'] = $order_info['order_id'];
                $log['order_sn'] = $order_info['order_sn'];
                $log['money'] = $rates;
                $log['type'] = 1;
                $log['description'] = '下级店铺利润返佣收入';
                $log['addtime'] = time();
                $result = $model_brokerage_log->addStoreLog($log);
                if (!$result) {
                    throw new Exception('写入日志失败');
                }
            }
        }
    }
}

//处理代理返佣
function dealAgentBrokerage($order_info, $member_info, $settings)
{
    $model_member = Model('member');
    $model_brokerage_log = Model('brokerage_log');
    $model_agent = Model('agent');

    $agents = $model_agent->getCache();
    $arr = [];
    if (!empty($agents[2])) {
        foreach ($agents[2] as $v) {
            if ($member_info['member_cityid'] == $v['city_id']) {
                $arr[$v['member_id']]['rates'] = $order_info['city_rates'];
                $arr[$v['member_id']]['aid'] = $v['id'];
                $arr[$v['member_id']]['invite'] = $v['invite_id'];
                $arr[$v['member_id']]['type'] = 2;
            }
        }
    }
    if (!empty($agents[3])) {
        foreach ($agents[3] as $v) {
            if ($member_info['member_areaid'] == $v['area_id']) {
                $arr[$v['member_id']]['rates'] = $order_info['area_rates'];
                $arr[$v['member_id']]['aid'] = $v['id'];
                $arr[$v['member_id']]['invite'] = $v['invite_id'];
                $arr[$v['member_id']]['type'] = 3;
            }
        }
    }
    if (!empty($agents[4])) {
        foreach ($agents[4] as $v) {
            if ($member_info['member_areaid'] == $v['area_id']) {
                $arr[$v['member_id']]['rates'] = $order_info['ty_rates'];
                $arr[$v['member_id']]['aid'] = $v['id'];
                $arr[$v['member_id']]['invite'] = $v['invite_id'];
                $arr[$v['member_id']]['type'] = 4;
            }
        }
    }
    if (empty($arr)) {
        return true;
    }
    //代理佣金处理
    foreach ($arr as $k => $v) {
        if (!isset($v['aid'])) {
            continue;
        }
        if (!$v['rates']) {
            continue;
        }
        $data = [];
        if (isset($order_info['member_rates'])) {
            $data['agent_sq_brokerage'] = ['exp', 'agent_sq_brokerage+' . $v['rates']];
            $data['av_agent_sq_brokerage'] = ['exp', 'av_agent_sq_brokerage+' . $v['rates']];
        } else {
            $data['agent_pt_brokerage'] = ['exp', 'agent_pt_brokerage+' . $v['rates']];
            $data['av_agent_pt_brokerage'] = ['exp', 'av_agent_pt_brokerage+' . $v['rates']];
        }
        $result = $model_member->editMember(['member_id' => $k], $data);
        if (!$result) {
            throw new Exception('会员信息更新失败');
        }
        $log = [];
        //写入分销佣金日志
        $log['member_id'] = $k;
        $log['agent_id'] = $v['aid'];
        $log['order_id'] = $order_info['order_id'];
        $log['order_sn'] = $order_info['order_sn'];
        $log['money'] = $v['rates'];
        $log['type'] = 1;
        $log['category'] = isset($order_info['member_rates']) ? 1 : 0;
        $log['description'] = '所属区域用户消费返佣收入';
        $log['addtime'] = time();
        $result = $model_brokerage_log->addAgentLog($log);
        if (!$result) {
            throw new Exception('写入日志失败');
        }
        if ($v['invite']) {
            $invite_type = 3;
            foreach ($agents as $m => $n) {
                if ($m > 1) {
                    foreach ($agents[$m] as $i => $j) {
                        if ($j['member_id'] == $v['invite']) {
                            $invite_type = $j['type'];
                        }
                    }
                }
            }
            $data = [];
            $fx_dl_invite = 0;
            if ($invite_type == 2) {
                $fx_dl_invite = $settings['fx_dl_city_invite'];
            }
            if ($invite_type == 3) {
                $fx_dl_invite = $settings['fx_dl_area_invite'];
            }
            if ($invite_type == 4) {
                $fx_dl_invite = $settings['fx_dl_ty_invite'];
            }

            $rates = round($fx_dl_invite * $v['rates'] / 100, 2);
            if (isset($order_info['member_rates'])) {
                $data['agent_sq_brokerage'] = ['exp', 'agent_sq_brokerage+' . $rates];
                $data['av_agent_sq_brokerage'] = ['exp', 'av_agent_sq_brokerage+' . $rates];
            } else {
                $data['agent_pt_brokerage'] = ['exp', 'agent_pt_brokerage+' . $rates];
                $data['av_agent_pt_brokerage'] = ['exp', 'av_agent_pt_brokerage+' . $rates];
            }
            $result = $model_member->editMember(['member_id' => $v['invite']], $data);
            if (!$result) {
                throw new Exception('会员信息更新失败');
            }
            $log = [];
            //写入分销佣金日志
            $log['member_id'] = $v['invite'];
            $log['agent_id'] = $v['aid'];
            $log['order_id'] = $order_info['order_id'];
            $log['order_sn'] = $order_info['order_sn'];
            $log['money'] = $rates;
            $log['type'] = 1;
            $log['category'] = isset($order_info['member_rates']) ? 1 : 0;
            $log['description'] = '推荐代理收益返佣收入';
            $log['addtime'] = time();
            $result = $model_brokerage_log->addAgentLog($log);
            if (!$result) {
                throw new Exception('写入日志失败');
            }
        }
    }
}

function dealSqBrokerage($order_info, $score = 0)
{

    //非商圈订单直接返回
    if (!isset($order_info['member_rates'])) {
        return true;
    }
    $model_member = Model('member');
    $model_store = Model('store');
    $model_brokerage_log = Model('brokerage_log');
    //消费者返利
    if ($order_info['member_rates']) {
        $data['brokerage'] = ['exp', 'brokerage+' . $order_info['member_rates']];
        $data['av_brokerage'] = ['exp', 'av_brokerage+' . $order_info['member_rates']];
        $result = $model_member->editMember(['member_id' => $order_info['buyer_id']], $data);
        if (!$result) {
            throw new Exception('会员信息更新失败');
        }
        //写入分销佣金日志
        $log['member_id'] = $order_info['buyer_id'];
        $log['order_id'] = $order_info['order_id'];
        $log['order_sn'] = $order_info['order_sn'];
        $log['money'] = $order_info['member_rates'];
        $log['type'] = 1;
        $log['description'] = '商圈购物消费返利';
        $log['addtime'] = time();
        $result = $model_brokerage_log->addMemberLog($log);
        if (!$result) {
            throw new Exception('写入日志失败');
        }
    }
    $store_info = $model_store->getStoreInfo(['store_id' => $order_info['store_id']]);
    //推荐商圈商户一级返利
    if ($score > 2 && $order_info['sq_store_rates']) {
        $sq_store_one = $model_store->getStoreInfo(['store_id' => $store_info['invite']]);
        $data = [];
        $data['sq_brokerage'] = ['exp', 'sq_brokerage+' . $order_info['sq_store_rates']];
        $data['av_sq_brokerage'] = ['exp', 'av_sq_brokerage+' . $order_info['sq_store_rates']];
        $result = $model_member->editMember(['member_id' => $sq_store_one['member_id']], $data);
        if (!$result) {
            throw new Exception('会员信息更新失败');
        }
        $log = [];
        //写入分销佣金日志
        $log['member_id'] = $sq_store_one['member_id'];
        $log['store_id'] = $store_info['invite'];
        $log['order_id'] = $order_info['order_id'];
        $log['order_sn'] = $order_info['order_sn'];
        $log['money'] = $order_info['sq_store_rates'];
        $log['type'] = 1;
        $log['description'] = '商圈店铺一级返利';
        $log['addtime'] = time();
        $result = $model_brokerage_log->addSqLog($log);
        if (!$result) {
            throw new Exception('写入日志失败');
        }
    }
    //推荐商圈商户二级返利
    if ($score > 2 && $order_info['sq_store_rates_two']) {
        $sq_store_two = $model_store->getStoreInfo(['store_id' => $store_info['invite_two']]);
        $data = [];
        $data['sq_brokerage'] = ['exp', 'sq_brokerage+' . $order_info['sq_store_rates_two']];
        $data['av_sq_brokerage'] = ['exp', 'av_sq_brokerage+' . $order_info['sq_store_rates_two']];
        $result = $model_member->editMember(['member_id' => $sq_store_two['member_id']], $data);
        if (!$result) {
            throw new Exception('会员信息更新失败');
        }
        $log = [];
        //写入分销佣金日志
        $log['member_id'] = $sq_store_two['member_id'];
        $log['store_id'] = $store_info['invite_two'];
        $log['order_id'] = $order_info['order_id'];
        $log['order_sn'] = $order_info['order_sn'];
        $log['money'] = $order_info['sq_store_rates_two'];
        $log['type'] = 1;
        $log['description'] = '商圈店铺二级返利';
        $log['addtime'] = time();
        $result = $model_brokerage_log->addSqLog($log);
        if (!$result) {
            throw new Exception('写入日志失败');
        }
    }

}

//处理自助开店后续操作
function dealOpenStore($member_id, $order_id)
{
    $settings = Model('setting')->getListSetting();
    $model_member = Model('member');
    $model_store = Model('store');
    $model_pd = Model('predeposit');
    $model_point = Model('points');
    $model_order = Model('order');
    $member_info = $model_member->getMemberInfoByID($member_id);
    $store = $model_store->getStoreInfo(['member_id' => $member_info['lev1']]);
    $invite_info = $model_member->getMemberInfoByID($member_info['lev1']);
    $point = 0;
    $cash = 0;
    //店铺二级分类：1.微店长2.平台经理3.平台总监4.平台董事
    switch ($store['type']) {
        case 1 :
            $point = $settings['fx_st_point_one'];
            $cash = $settings['fx_st_cash_one'];
            break;
        case 2 :
            $point = $settings['fx_st_point_two'];
            $cash = $settings['fx_st_cash_two'];
            break;
        case 3 :
            $point = $settings['fx_st_point_three'];
            $cash = $settings['fx_st_cash_three'];
            break;
        case 4 :
            $point = $settings['fx_st_point_four'];
            $cash = $settings['fx_st_cash_four'];
            break;
    }
    //关联开店
    if ($store) {
        $model_member->editMember(['member_id' => $member_id], ['invite_store' => $member_info['lev1']]);
    }
    //奖励辅导工资
    if ($cash) {
        $data['amount'] = $cash;
        $data['member_id'] = $invite_info['member_id'];
        $data['member_name'] = $invite_info['member_name'];
        $model_pd->changePd('invite_store', $data);
    }
    if ($point) {
        //赠送开店积分
        $insertarr['pl_points'] = $point;
        $insertarr['pl_memberid'] = $member_id;
        $insertarr['pl_membername'] = $member_info['member_name'];
        $model_point->savePointsLog('open_store', $insertarr);
    }
    //订单状态更新为已评论和佣金发放
    $model_order->editOrder(['order_state' => ORDER_STATE_SUCCESS], ['order_id' => $order_id]);
    $return = Logic('member_evaluate')->validation($order_id, $member_id);
    if (!$return['state']) {
        return true;
    }
    extract($return['data']);
    $return = Logic('member_evaluate')->save($_POST, $order_info, $store_info, $order_goods, $member_id, $member_info['member_name']);
    if (!$return['state']) {
        return true;
    }
    //评价结算佣金
    brokerageBill($order_info, 5);
}


//$type: 0.完成订单  1.取消订单
function addPointsLog($order_info, $type = 0)
{
    if (!$order_info['use_points']) {
        return true;
    }
    $model_points = Model('points');
    //新增日志
    $value_array = array();
    $value_array['pl_memberid'] = $order_info['buyer_id'];
    $value_array['pl_membername'] = $order_info['buyer_name'];
    $value_array['pl_points'] = -$order_info['use_points'];
    $value_array['pl_addtime'] = time();
    $value_array['pl_desc'] = '兑换专区商品积分抵扣现金';
    if ($type) {
        $value_array['pl_points'] = $order_info['use_points'];
        $value_array['pl_desc'] = '兑换专区订单取消返还积分';
    }
    $value_array['pl_stage'] = 'order';
    $result = $model_points->addPointsLog($value_array);
    if (!$result) {
        throw new Exception('写入日志失败');
    }
    if ($type) {
        $model_member = Model('member');
        //返还积分
        $model_member->editMember(['member_id' => $order_info['buyer_id']], ['member_points' => array('exp', 'member_points+' . $order_info['use_points'])]);
    }
}

//$type: 退款积分返还
function addReturnPointsLog($order_info, $points, $type)
{
    $model_points = Model('points');
    //新增日志
    $value_array = array();
    $value_array['pl_memberid'] = $order_info['buyer_id'];
    $value_array['pl_membername'] = $order_info['buyer_name'];
    $value_array['pl_points'] = -$points;
    $value_array['pl_addtime'] = time();
    $value_array['pl_desc'] = "订单" . $order_info['order_sn'] . "退款返还积分";
    $value_array['pl_stage'] = 'order';
    if ($type) {
        $value_array['pl_desc'] = "订单" . $order_info['order_sn'] . "退款评价返还积分";
    }
    $result = $model_points->addPointsLog($value_array);
    if (!$result) {
        throw new Exception('写入日志失败');
    }
    $model_member = Model('member');
    //返还积分给平台
    $model_member->editMember(['member_id' => $order_info['buyer_id']], ['member_points' => array('exp', 'member_points-' . $points)]);
}


function tolog($data, $myfile = '')
{
    is_array($data) ? $str = var_export($data, TRUE) : $str = $data;
    $myfile == '' ? $file = BASE_ROOT_PATH . '/log.txt' : $file = $myfile;
    if ($myfile != '' && !file_exists($myfile)) {
        throw new Exception("Function < tolog > Error : The File Or The FilePath Is Not Exists !");
    }
    file_put_contents($file, $str . "\r\n", FILE_APPEND);
}

//佣金退还
function rollbackrates($orderInfo)
{
    //没有佣金的订单直接返回
    if (!$orderInfo['invite_rates'] && !$orderInfo['store_rates'] && !$orderInfo['city_rates'] && !(isset($orderInfo['sq_store_rates']) && $orderInfo['sq_store_rates'])) {
        return true;
    }
    $prefix = C('tablepre');
    $sql = ' UPDATE ' . $prefix . 'member ';
    $sql_brokerage = '';                     //会员佣金
    $sql_av_brokerage = '';                  //会员可用佣金
    $sql_store_brokerage = '';               //小店佣金
    $sql_av_store_brokerage = '';            //小店可用佣金
    $sql_agent_pt_brokerage = '';            //代理平台佣金
    $sql_av_agent_pt_brokerage = '';         //代理可用平台佣金
    $sql_agent_sq_brokerage = '';            //代理商圈佣金
    $sql_av_agent_sq_brokerage = '';         //代理商圈可用佣金
    $sql_sq_brokerage = '';                  //商圈佣金
    $sql_av_sq_brokerage = '';               //商圈可用佣金

    $data = [];  //日志数据
    $ids = [];   //会员id
    $res = [];   //结果集

    $model_member = Model('member');
    $model_brokerage_log = Model('brokerage_log');

    $where['order_sn'] = $orderInfo['order_sn'];
    $where['type'] = 1;

    if ($orderInfo['invite_rates']) {
        //退还会员佣金
        $res['member'] = $model_brokerage_log->getMemberLogList($where);
    }
    if ($orderInfo['store_rates']) {
        //退还小店佣金
        $res['store'] = $model_brokerage_log->getStoreLogList($where);
    }
    if ($orderInfo['city_rates']) {
        //退还代理佣金
        $res['agent'] = $model_brokerage_log->getAgentLogList($where);
    }
    if (isset($orderInfo['sq_store_rates']) && $orderInfo['sq_store_rates']) {
        //退还商圈小店佣金
        $res['sq'] = $model_brokerage_log->getSqLogList($where);
    }
    if (empty($res)) {
        return true;
    }
    foreach ($res as $v) {
        if (!empty($v)) {
            foreach ($v as $j) {
                $ids[] = $j['member_id'];
            }
        }
    }
    $ids = array_values(array_unique($ids));
    foreach ($res as $k => $v) {
        if (empty($v)) {
            continue;
        }
        switch ($k) {
            case 'member' :
                $sql_brokerage .= ' SET brokerage = CASE member_id ';
                $sql_av_brokerage .= 'av_brokerage = CASE member_id ';
                foreach ($v as $m) {
                    $data['member'][$m['member_id']] = ['money' => $m['money']];
                    $sql_brokerage .= ' WHEN ' . $m['member_id'] . ' THEN `brokerage` - ' . $m['money'];
                    $sql_av_brokerage .= ' WHEN ' . $m['member_id'] . ' THEN `av_brokerage` - ' . $m['money'];
                }
                $arr_ids = array_column($v, 'member_id');
                $dff_ids = array_diff($ids, $arr_ids);
                if (!empty($dff_ids)) {
                    foreach ($dff_ids as $n) {
                        $sql_brokerage .= ' WHEN ' . $n . ' THEN `brokerage` - ' . 0;
                        $sql_av_brokerage .= ' WHEN ' . $n . ' THEN `av_brokerage` - ' . 0;
                    }
                }
                $sql_brokerage .= ' END';
                $sql_av_brokerage .= ' END';
                break;
            case 'store' :
                if ($sql_brokerage) {
                    $sql_store_brokerage .= ' store_brokerage = CASE member_id ';
                } else {
                    $sql_store_brokerage .= ' SET store_brokerage = CASE member_id ';
                }
                $sql_av_store_brokerage .= 'av_store_brokerage = CASE member_id ';
                foreach ($v as $m) {
                    $data['store'][$m['member_id']] = ['money' => $m['money'], 'store_id' => $m['store_id']];
                    $sql_store_brokerage .= ' WHEN ' . $m['member_id'] . ' THEN `store_brokerage` - ' . $m['money'];
                    $sql_av_store_brokerage .= ' WHEN ' . $m['member_id'] . ' THEN `av_store_brokerage` - ' . $m['money'];
                }

                $arr_ids = array_column($v, 'member_id');
                $dff_ids = array_diff($ids, $arr_ids);
                if (!empty($dff_ids)) {
                    foreach ($dff_ids as $n) {
                        $sql_store_brokerage .= ' WHEN ' . $n . ' THEN `store_brokerage` - ' . 0;
                        $sql_av_store_brokerage .= ' WHEN ' . $n . ' THEN `av_store_brokerage` - ' . 0;
                    }
                }

                $sql_store_brokerage .= ' END';
                $sql_av_store_brokerage .= ' END';
                break;
            case 'agent' :
                if ($orderInfo['member_rates']) {
                    if ($sql_brokerage || $sql_store_brokerage) {
                        $sql_agent_sq_brokerage .= ' agent_sq_brokerage = CASE member_id ';
                    } else {
                        $sql_agent_sq_brokerage .= ' SET agent_sq_brokerage = CASE member_id ';
                    }
                    $sql_av_agent_sq_brokerage .= ' av_agent_sq_brokerage = CASE member_id ';
                    foreach ($v as $m) {
                        $data['agent'][$m['member_id']] = ['money' => $m['money'], 'agent_id' => $m['agent_id'], 'category' => $m['category']];
                        $sql_agent_sq_brokerage .= ' WHEN ' . $m['member_id'] . ' THEN `agent_sq_brokerage` - ' . $m['money'];
                        $sql_av_agent_sq_brokerage .= ' WHEN ' . $m['member_id'] . ' THEN `av_agent_sq_brokerage` - ' . $m['money'];
                    }

                    $arr_ids = array_column($v, 'member_id');
                    $dff_ids = array_diff($ids, $arr_ids);
                    if (!empty($dff_ids)) {
                        foreach ($dff_ids as $n) {
                            $sql_agent_sq_brokerage .= ' WHEN ' . $n . ' THEN `agent_sq_brokerage` - ' . 0;
                            $sql_av_agent_sq_brokerage .= ' WHEN ' . $n . ' THEN `av_agent_sq_brokerage` - ' . 0;
                        }
                    }

                    $sql_agent_sq_brokerage .= ' END';
                    $sql_av_agent_sq_brokerage .= ' END';
                } else {
                    if ($sql_brokerage || $sql_store_brokerage) {
                        $sql_agent_pt_brokerage .= ' agent_pt_brokerage = CASE member_id ';
                    } else {
                        $sql_agent_pt_brokerage .= ' SET agent_pt_brokerage = CASE member_id ';
                    }
                    $sql_av_agent_pt_brokerage .= ' av_agent_pt_brokerage = CASE member_id ';
                    foreach ($v as $m) {
                        $data['agent'][$m['member_id']] = ['money' => $m['money'], 'agent_id' => $m['agent_id'], 'category' => $m['category']];
                        $sql_agent_pt_brokerage .= ' WHEN ' . $m['member_id'] . ' THEN `agent_pt_brokerage` - ' . $m['money'];
                        $sql_av_agent_pt_brokerage .= ' WHEN ' . $m['member_id'] . ' THEN `av_agent_pt_brokerage` - ' . $m['money'];
                    }

                    $arr_ids = array_column($v, 'member_id');
                    $dff_ids = array_diff($ids, $arr_ids);
                    if (!empty($dff_ids)) {
                        foreach ($dff_ids as $n) {
                            $sql_agent_pt_brokerage .= ' WHEN ' . $n . ' THEN `agent_pt_brokerage` - ' . 0;
                            $sql_av_agent_pt_brokerage .= ' WHEN ' . $n . ' THEN `av_agent_pt_brokerage` - ' . 0;
                        }
                    }

                    $sql_agent_pt_brokerage .= ' END';
                    $sql_av_agent_pt_brokerage .= ' END';
                }
                break;
            case 'sq' :
                if ($sql_brokerage || $sql_store_brokerage || $sql_agent_pt_brokerage || $sql_agent_sq_brokerage) {
                    $sql_sq_brokerage .= ' sq_brokerage = CASE member_id ';
                } else {
                    $sql_sq_brokerage .= ' SET sq_brokerage = CASE member_id ';
                }
                $sql_av_sq_brokerage .= 'av_sq_brokerage = CASE member_id ';
                foreach ($v as $m) {
                    $data['sq'][$m['member_id']] = ['money' => $m['money'], 'store_id' => $m['store_id']];
                    $sql_sq_brokerage .= ' WHEN ' . $m['member_id'] . ' THEN `sq_brokerage` - ' . $m['money'];
                    $sql_av_sq_brokerage .= ' WHEN ' . $m['member_id'] . ' THEN `av_sq_brokerage` - ' . $m['money'];
                }

                $arr_ids = array_column($v, 'member_id');
                $dff_ids = array_diff($ids, $arr_ids);
                if (!empty($dff_ids)) {
                    foreach ($dff_ids as $n) {
                        $sql_sq_brokerage .= ' WHEN ' . $n . ' THEN `sq_brokerage` - ' . 0;
                        $sql_av_sq_brokerage .= ' WHEN ' . $n . ' THEN `av_sq_brokerage` - ' . 0;
                    }
                }

                $sql_sq_brokerage .= ' END';
                $sql_av_sq_brokerage .= ' END';
                break;
        }
    }
    if (!$sql_brokerage && !$sql_av_brokerage && !$sql_store_brokerage && !$sql_av_store_brokerage && !$sql_agent_pt_brokerage && !$sql_av_agent_pt_brokerage && !$sql_agent_sq_brokerage && !$sql_av_agent_sq_brokerage && !$sql_sq_brokerage && !$sql_av_sq_brokerage) {
        return true;
    }
    //拼接sql语句
    $sql .= $sql_brokerage ? $sql_brokerage . ', ' : '';
    $sql .= $sql_av_brokerage ? $sql_av_brokerage . ', ' : '';
    $sql .= $sql_store_brokerage ? $sql_store_brokerage . ', ' : '';
    $sql .= $sql_av_store_brokerage ? $sql_av_store_brokerage . ', ' : '';
    $sql .= $sql_agent_pt_brokerage ? $sql_agent_pt_brokerage . ', ' : '';
    $sql .= $sql_av_agent_pt_brokerage ? $sql_av_agent_pt_brokerage . ', ' : '';
    $sql .= $sql_agent_sq_brokerage ? $sql_agent_sq_brokerage . ', ' : '';
    $sql .= $sql_av_agent_sq_brokerage ? $sql_av_agent_sq_brokerage . ', ' : '';
    $sql .= $sql_sq_brokerage ? $sql_sq_brokerage . ', ' : '';
    $sql .= $sql_av_sq_brokerage ? $sql_av_sq_brokerage . ', ' : '';
    $sql = trim($sql, ', ');
    if (empty($ids)) {
        return true;
    }
    $ids = implode(',', $ids);
    $sql .= ' WHERE member_id IN ( ' . $ids . ' )';
    //开始事务
    $model_member->beginTransaction();
    try {
        //执行退还佣金
        $res = $model_member->execute($sql);
        //写入佣金日志
        foreach ($data as $k => $v) {
            foreach ($v as $m => $n) {
                $log = [];
                $log['member_id'] = $m;
                $log['order_id'] = $orderInfo['order_id'];
                $log['order_sn'] = $orderInfo['order_sn'];
                $log['money'] = $n['money'];
                $log['type'] = 2;
                $log['description'] = '订单退货佣金减扣';
                $log['addtime'] = time();
                switch ($k) {
                    case 'member' :
                        //写入分销佣金日志
                        $model_brokerage_log->addMemberLog($log);
                        break;
                    case 'store' :
                        //写入分销佣金日志
                        $log['store_id'] = $n['store_id'];
                        $model_brokerage_log->addStoreLog($log);
                        break;
                    case 'agent' :
                        //写入分销佣金日志
                        $log['agent_id'] = $n['agent_id'];
                        $log['category'] = $n['category'];
                        $model_brokerage_log->addAgentLog($log);
                        break;
                    case 'sq' :
                        //写入分销佣金日志
                        $log['store_id'] = $n['store_id'];
                        $model_brokerage_log->addSqLog($log);
                        break;
                }
            }
        }

        //提交事务
        $model_member->commit();
        return true;
    } catch (Exception $e) {
        //回滚事务
        $model_member->rollback();
        return false;
    }

}